package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.GeConIntegralGoodsMapper;
import com.htgd.gardenexpo.dao.GeConIntegralGoodsOrderMapper;
import com.htgd.gardenexpo.dto.GeConIntegralGoodsDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.GoodsQuery;
import com.htgd.gardenexpo.service.*;
import com.htgd.gardenexpo.utils.GoodsOrderNoUtils;
import com.htgd.gardenexpo.vo.GeConIntegralGoodsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author: 王秀田
 * @date: 2024/11/13 17:16
 * @description: TODO
 */
@Service
public class GeConIntegralGoodsServiceImpl extends ServiceImpl<GeConIntegralGoodsMapper, GeConIntegralGoods> implements GeConIntegralGoodsService {

    @Autowired
    private GeConIntegralGoodsMapper geConIntegralGoodsMapper;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private GeMyAddressService geMyAddressService;

    @Autowired
    private GeConIntegralGoodsOrderService geConIntegralGoodsOrderService;

    @Autowired
    private GeConIntegralGetDetailsService geConIntegralGetDetailsService;

    /**
     * 添加积分商品
     * @param geConIntegralGoods
     */
    @Transactional
    @Override
    public void add(GeConIntegralGoodsDTO geConIntegralGoods) {
        GeConIntegralGoods goods = new GeConIntegralGoods();
        BeanUtils.copyProperties(geConIntegralGoods,goods);
        goods.setCreateTime(LocalDateTime.now());
        goods.setStatus("0");
        goods.setDeleteFlag("0");
        List<String> images = geConIntegralGoods.getImages();
        if(!images.isEmpty()){
            goods.setPicture(JSON.toJSON(images).toString());
        }
        save(goods);
    }

    /**
     * 查询积分商品列表
     * @param goodsQuery
     * @return
     */
    @Override
    public PageInfo<GeConIntegralGoods> pageList(GoodsQuery goodsQuery) {
        PageHelper.startPage(goodsQuery.getPageNum(), goodsQuery.getPageSize());
        List<GeConIntegralGoods> list = geConIntegralGoodsMapper.pageList(goodsQuery);
        if(!list.isEmpty()){
            list.stream().forEach(item->{
                if(Objects.equals(item.getStatus(),"0")){
                    item.setStatusText("下架");
                }else{
                    item.setStatusText("上架");
                }
                if(Objects.equals(item.getDeleteFlag(),"0")){
                    item.setDeleteFlagText("正常");
                }else{
                    item.setDeleteFlagText("已删除");
                }
                item.setTypeText(geBaseDictService.getGoodsType(item.getType()));
                item.setImages(JSONArray.parseArray(item.getPicture(),String.class));
            });
        }
        return new PageInfo<>(list);
    }

    /**
     * 获取预提交信息
     * @return
     */
    @Override
    public CommonResult<GeConIntegralGoodsVO> prepareSubmit(String goodsId, Integer num, String openId) {
        CommonResult<GeConIntegralGoodsVO> result = new CommonResult<>();
        GeConIntegralGoodsVO geConIntegralGoodsVO = new GeConIntegralGoodsVO();
        GeConIntegralGoods goods = geConIntegralGoodsMapper.selectById(goodsId);
        //判断是否下架
        if("0".equals(goods.getStatus())){
            return CommonResult.error("该商品已下架，无法兑换");
        }
        if(goods.getNum()<num){
            result.setCode(500);
            result.setMessage("积分商品库存不足");
            return result;
        }
        WxUser user = wxUserService.getOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId,openId));
        if(user.getIntegralNum()<num*goods.getIntegral()){
            result.setCode(500);
            result.setMessage("您的积分余额不足");
            return result;
        }
        geConIntegralGoodsVO.setId(goods.getId());
        geConIntegralGoodsVO.setName(goods.getName());
        geConIntegralGoodsVO.setTypeText(geBaseDictService.getGoodsType(goods.getType()));
        geConIntegralGoodsVO.setIntegral(goods.getIntegral());
        geConIntegralGoodsVO.setNum(num);
        geConIntegralGoodsVO.setTotalIntegral(num*goods.getIntegral());
        geConIntegralGoodsVO.setImages(JSONArray.parseArray(goods.getPicture(),String.class));
        GeMyAddress geMyAddress = geMyAddressService.getOne(new LambdaQueryWrapper<GeMyAddress>()
            .eq(GeMyAddress::getOpenId,openId)
            .eq(GeMyAddress::getStatus,1)
            .eq(GeMyAddress::getDeleteFlag,"0"));
        geConIntegralGoodsVO.setGeMyAddress(geMyAddress);
        result.setCode(200);
        result.setMessage("预提交成功");
        result.setData(geConIntegralGoodsVO);
        return result;
    }

    /**
     * 积分商品确定支付
     * @param goods
     * @param openId
     * @return
     */
    @Transactional
    @Override
    public synchronized CommonResult<GeConIntegralGoodsOrder> goodsSubmit(GeConIntegralGoods goods, String openId) {
        CommonResult<GeConIntegralGoodsOrder> result = new CommonResult<>();
        try {
            GeConIntegralGoods geConIntegralGoods = geConIntegralGoodsMapper.selectById(goods.getId());
            if(geConIntegralGoods.getNum()<goods.getNum()){
                result.setCode(500);
                result.setMessage("积分商品库存不足");
                return result;
            }
            WxUser user = wxUserService.getOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId,openId));
            if(user.getIntegralNum()<geConIntegralGoods.getIntegral()*goods.getNum()){
                result.setCode(500);
                result.setMessage("您的积分余额不足");
                return result;
            }
            GeMyAddress geMyAddress = geMyAddressService.getById(goods.getAddressId());
            //新建订单
            GeConIntegralGoodsOrder order = new GeConIntegralGoodsOrder();
            order.setCreateTime(LocalDateTime.now());
            order.setOrderNum(GoodsOrderNoUtils.getIntegralGoodsNum());
            order.setRemark(goods.getRemark());
            order.setStatus("0");
            order.setGoodsId(geConIntegralGoods.getId());
            order.setAddressId(goods.getAddressId());
            order.setOpenId(openId);
            order.setName(geMyAddress.getName());
            order.setPhone(geMyAddress.getPhone());
            order.setRegion(geMyAddress.getRegion());
            order.setDetail(geMyAddress.getDetail());
            order.setGoodsName(geConIntegralGoods.getName());
            order.setPicture(geConIntegralGoods.getPicture());
            order.setIntegral(geConIntegralGoods.getIntegral());
            order.setTotalIntegral(goods.getNum()*geConIntegralGoods.getIntegral());
            order.setDetails(geConIntegralGoods.getDetails());
            order.setNum(goods.getNum());
            order.setType(geConIntegralGoods.getType());
            geConIntegralGoodsOrderService.save(order);
            //减库存，添加兑换数量
            GeConIntegralGoods integralGoods = new GeConIntegralGoods();
            integralGoods.setId(geConIntegralGoods.getId());
            integralGoods.setNum(geConIntegralGoods.getNum()-goods.getNum());
            integralGoods.setAlreadyNum(geConIntegralGoods.getAlreadyNum()+goods.getNum());
            updateById(integralGoods);
            //扣除用户积分
            LambdaUpdateWrapper<WxUser> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.set(WxUser::getIntegralNum,user.getIntegralNum()-goods.getNum()*geConIntegralGoods.getIntegral());
            updateWrapper.eq(WxUser::getOpenId, openId);
            wxUserService.update(null,updateWrapper);
            //积分消费记录
            GeConIntegralGetDetails geConIntegralGetDetails = new GeConIntegralGetDetails();
            geConIntegralGetDetails.setCreateTime(LocalDateTime.now());
            geConIntegralGetDetails.setGoodsName(geConIntegralGoods.getName());
            if(goods.getNum()*geConIntegralGoods.getIntegral()!=0){
                int negativeNum = -Math.abs(goods.getNum()*geConIntegralGoods.getIntegral());
                geConIntegralGetDetails.setConsumeNum(Integer.valueOf(negativeNum));
            }else{
                geConIntegralGetDetails.setConsumeNum(0);
            }
            geConIntegralGetDetails.setAmount(goods.getNum());
            geConIntegralGetDetails.setOpenId(openId);
            geConIntegralGetDetails.setMethod("积分商城兑换");
            geConIntegralGetDetails.setOrderNum(order.getOrderNum());
            geConIntegralGetDetailsService.save(geConIntegralGetDetails);
            order.setTypeText(geBaseDictService.getGoodsType(goods.getType()));
            order.setImages(JSONArray.parseArray(geConIntegralGoods.getPicture(),String.class));
            result.setCode(200);
            result.setMessage("兑换成功");
            result.setData(order);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("兑换失败");
        }
        return result;
    }
}
